/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.weso.acota.dao;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeIterator;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.to.TagTO;
import org.weso.acota.utils.DocumentBuilderHelper;

/**
 *
 * @author chema
 */
public class GoogleSuggestDAOImpl implements SuggestDAO {

    private String googleUrl = "http://google.com/complete/search?output=toolbar&q=";


    @Override
    public SuggestionTO suggest(RequestSuggestionTO request) {
        NodeIterator it;
        try {
            URL url = new URL(this.googleUrl + request.getWord());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "application/xml");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK
                    && connection.getContentType().contains("text/xml"))
            {
                InputStream is = connection.getInputStream();
                //XML
                SuggestionTO suggestion = new SuggestionTO();
                Document result = DocumentBuilderHelper.getDocumentFromInputStream(is);
                it = org.apache.xpath.XPathAPI.selectNodeIterator(result, "//suggestion/@data");
                Node n = it.nextNode();
                List<TagTO> tags = new LinkedList<TagTO>();
                while(n != null){
                    tags.add(new TagTO(GoogleSuggestDAOImpl.class.getSimpleName(),n.getTextContent()));
                    n = it.nextNode();
                }
                suggestion.setTags(tags);
                return suggestion;
            } else {
                throw new RuntimeException("Unable to get a representation of the resource");
            }
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }
}
